//
//  CPUserAccountViewModel.swift
//  weibo
//
//  Created by zcp on 16/5/13.
//  Copyright © 2016年 zcp. All rights reserved.
//

import UIKit

class CPUserAccountViewModel: NSObject {
    //单例
    static let sharedAccountViewModel: CPUserAccountViewModel = CPUserAccountViewModel()
    //保存解档后模型,方便外面拿到这个
    var userAccount: CPUserAccount?
    
    //外界一创建这个对象时,就解档并保存到属性中
    override init() {
        super.init()
        userAccount = loadAccount()
    }

    //是否登录账号
    func isLogin() -> Bool{
    
        //解档时,有账号,就表示登录了
        userAccount = loadAccount()
        return userAccount != nil
    
    }
    //解档,归档的路径
    let path = NSSearchPathForDirectoriesInDomains( NSSearchPathDirectory.DocumentDirectory,  NSSearchPathDomainMask.UserDomainMask, true).last!+"/account.plist"
    
    /**
    发送POST请求获取accessToken
    */
    func loadAccessToken(code: String,callBack: (error: NSError?)->()){
        let urlString = "oauth2/access_token"
        let parameters = [
            
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        
        CPNetworkTool.sharedNetworkTool.request(requsetMethod.POST, URLString: urlString, parameters: parameters, success: { (task,responseObject) -> Void in
            //判断返回数据能不能转为字典
            if let dict = responseObject as? [String : AnyObject]
            {
                //字典转模型
                let account: CPUserAccount = CPUserAccount(dict: dict)
                //将模型归档保存沙盒中
//                print("\(account)")
                NSKeyedArchiver.archiveRootObject(account, toFile:self.path)
//                print("\(self.path)")
                //转换并保存成功
                callBack(error: nil)
                
            }
            else
            {
                print("数据转字典失败")
                
            }
            
            }, failure: { (task, error) -> Void in
                callBack(error: error)
        })
    
    }
    //解档
    func loadAccount() -> CPUserAccount?
    {
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(self.path) as? CPUserAccount
        {
             if account.expriseDate?.compare(NSDate()) != NSComparisonResult.OrderedAscending
             {
                //没有过期
                return account
             }
            else
             {
                //过期了
                return nil
             }
        }
        else
        {
            return nil
        }
    }
    
    //MARK: - 获取用户名称和头像
    func loadUserInfro(callback:() -> ()){
    
        //判断access_token有没有值,没值就走里面
        guard let access_token = userAccount?.access_token else{
        
            return
        }
        guard let uid = userAccount?.uid else {
        
            return
        }
        let urlString = "2/users/show.json"
        let parameters = [
        
            "access_token" : access_token,
            "uid" : uid
        ]
        //GET 请求数据
        CPNetworkTool.sharedNetworkTool.request(requsetMethod.GET, URLString: urlString, parameters: parameters, success: { (_, respose) -> Void in
//            print("\(respose)")
            //保存到模型
            if let result = respose as? [String : AnyObject]{
                self.userAccount?.screen_name = result["screen_name"] as? String
                self.userAccount?.avatar_large = result["avatar_large"] as? String
                //归档保存到沙盒
                NSKeyedArchiver.archiveRootObject(self.userAccount!, toFile: self.path)
//                print("路径\(self.path)")
                callback()
            }
            
            }) { (_, error) -> Void in
                print("获取用户名称和头像数据失败")
        }
    }
}
